package team.nmsg.log;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import team.nmsg.ge.system.bean.SysUser;
import team.nmsg.ge.system.init.CommonDefine;
import team.nmsg.ge.system.init.shiro.SysAuthorizingRealm;
import team.nmsg.ge.system.interf.IBusinessLogAddit;

@Aspect
@Component(value="ResourcesLogInterceptor")
public class ResourcesLogInterceptor {
	public static Log logger = LogFactory.getLog( ResourcesLogInterceptor.class );
	
	public static final Integer MODULE_ID = 3;
	
	@Pointcut("execution(public * team.nmsg.nps.res.**.service.*Service.*(..)) ")  
    public void addLogResourcesService(){}  
	
	
	@AfterReturning(value="addLogResourcesService()", returning="rtv")
	 public void addLogResourcesServiceCall(JoinPoint joinPoint, Object rtv) {
		
		try {
			Object[] args = joinPoint.getArgs();
			String methodName = joinPoint.getSignature().getName();
			
			Map<String, IBusinessLogAddit> map = CommonDefine.logAddits.get( MODULE_ID );
			if( map == null  ){
				return ;
			}
			IBusinessLogAddit iBusinessLogAddit = map.get(methodName);
			if( iBusinessLogAddit == null ){
				return;
			}
			
			HttpSession session = null;
			ServletRequestAttributes attr = null;
			try {
				attr = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
			} catch (Exception e) {
				logger.warn(	methodName + "RequestContextHolder.currentRequestAttributes()无法获取HttpRequest'");
				return;
			}
			HttpServletRequest request = attr.getRequest();
			
			logger.debug("Log For System Business [" + methodName+ "] Args is: "+ args);
			
			
			SysUser cUser = (SysUser) SysAuthorizingRealm.getShiroSessionAttr("user");
			iBusinessLogAddit.addBusinessLog(methodName, args, rtv, request , cUser);
			
		} catch( Exception e) {
			logger.error("team.nmsg.ge.system.log.ResourcesLogInterceptor.addLogResourcesServiceCall(JoinPoint, Object)" , e);
		}
		
	 }
	
}
